<template>
  <t-dialog
    :visible="visible"
    :header="title"
    :width="800"
    :footer="false"
    @update:visible="handleVisibleChange"
  >
    <t-form
      ref="form"
      :data="formData"
      :rules="rules"
      :label-width="100"
      @submit="onSubmit"
    >
      <t-row :gutter="[16, 16]">
        <t-col :span="12">
          <t-form-item name="name" label="合同名称">
            <t-input
              v-model="formData.name"
              placeholder="请输入合同名称"
              clearable
            />
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item name="type" label="合同类型">
            <t-select
              v-model="formData.type"
              placeholder="请选择合同类型"
              clearable
            >
              <t-option :value="1" label="主合同" />
              <t-option :value="2" label="子合同" />
              <t-option :value="3" label="补充合同" />
            </t-select>
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item name="paymentType" label="收付类型">
            <t-radio-group v-model="formData.paymentType">
              <t-radio :value="1">收款</t-radio>
              <t-radio :value="2">付款</t-radio>
            </t-radio-group>
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item name="amount" label="合同金额">
            <t-input-number
              v-model="formData.amount"
              placeholder="请输入合同金额"
              :min="0"
              :max="999999999"
              :step="1000"
            />
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item name="partyA" label="甲方">
            <t-input
              v-model="formData.partyA"
              placeholder="请输入甲方名称"
              clearable
            />
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item name="partyB" label="乙方">
            <t-input
              v-model="formData.partyB"
              placeholder="请输入乙方名称"
              clearable
            />
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item name="signDate" label="签订日期">
            <t-date-picker
              v-model="formData.signDate"
              placeholder="请选择签订日期"
              format="YYYY-MM-DD"
              :enableTimePicker="false"
            />
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item name="startDate" label="生效日期">
            <t-date-picker
              v-model="formData.startDate"
              placeholder="请选择生效日期"
              format="YYYY-MM-DD"
              :enableTimePicker="false"
            />
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item name="endDate" label="结束日期">
            <t-date-picker
              v-model="formData.endDate"
              placeholder="请选择结束日期"
              format="YYYY-MM-DD"
              :enableTimePicker="false"
            />
          </t-form-item>
        </t-col>

        <t-col :span="24">
          <t-form-item name="comment" label="备注">
            <t-textarea
              v-model="formData.comment"
              placeholder="请输入备注信息"
              :maxlength="500"
              :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </t-form-item>
        </t-col>
      </t-row>

      <div class="operation-container">
        <t-space>
          <t-button theme="primary" type="submit">确定</t-button>
          <t-button theme="default" @click="onCancel">取消</t-button>
        </t-space>
      </div>
    </t-form>
  </t-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { MessagePlugin, FormRule, SubmitContext } from 'tdesign-vue-next';
import { createContract, updateContract } from '@/api/contract';
import type { ContractInfo } from '@/api/contract';

const props = defineProps<{
  visible: boolean;
  type: 'add' | 'edit';
  formData?: Partial<ContractInfo>;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'success': [];
  'cancel': [];
}>();

const handleVisibleChange = (value: boolean) => {
  emit('update:visible', value);
};

const title = computed(() => props.type === 'add' ? '新增合同' : '编辑合同');

const form = ref();
const formData = ref<Partial<ContractInfo>>({});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  paymentType: [{ required: true, message: '请选择收付类型', trigger: 'change' }],
  amount: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
  partyA: [{ required: true, message: '请输入甲方名称', trigger: 'blur' }],
  partyB: [{ required: true, message: '请输入乙方名称', trigger: 'blur' }],
  signDate: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
} as Record<string, FormRule[]>;

watch(
  () => props.formData,
  (val) => {
    if (val) {
      formData.value = { ...val };
    }
  },
  { immediate: true }
);

// 表单提交
const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    try {
      if (props.type === 'add') {
        if (!formData.value.name || !formData.value.type || !formData.value.paymentType ||
            !formData.value.amount || !formData.value.partyA || !formData.value.partyB ||
            !formData.value.signDate || !formData.value.startDate || !formData.value.endDate) {
          MessagePlugin.error('请填写必填字段');
          return;
        }

        const data: ContractInfo = {
          name: formData.value.name,
          type: formData.value.type,
          paymentType: formData.value.paymentType,
          amount: formData.value.amount,
          partyA: formData.value.partyA,
          partyB: formData.value.partyB,
          signDate: formData.value.signDate,
          startDate: formData.value.startDate,
          endDate: formData.value.endDate,
          comment: formData.value.comment,
        };
        const res = await createContract(data);
        console.log('提交成功:', res);
        MessagePlugin.success('新增成功');
      } else {
        if (!formData.value.id) {
          MessagePlugin.error('缺少合同ID');
          return;
        }
        await updateContract({
          ...formData.value,
          id: formData.value.id,
        } as ContractInfo);
        MessagePlugin.success('更新成功');
      }
      emit('success');
    } catch (error) {
      console.error('提交失败:', error);
      MessagePlugin.error('提交失败');
    }
  } else if (ctx.firstError) {
    MessagePlugin.error(ctx.firstError);
  }
};

// 取消处理
const onCancel = () => {
  emit('cancel');
};
</script>

<style lang="less" scoped>
.operation-container {
  margin-top: 20px;
  text-align: right;
}

.t-form {
  padding: 24px;
}
</style>
